/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package caesar;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
/**
 * @author triasfahrudin
 */
public class CaesarEnc extends MIDlet implements CommandListener {

    private Form formMain;
    private Form formResult;
    private Display display;
    private TextField plaintext,shiftKey;
    private Command enc;
    
            
    public CaesarEnc(){
        plaintext = new TextField("Plain text", "", 30, TextField.ANY);
        shiftKey = new TextField("Shift Key", "",2, TextField.DECIMAL);
        enc = new Command("ENC",Command.OK,2);
        
    }
    
    public void startApp() {
        display = Display.getDisplay(this);
        formMain = new Form("Caesar Enc");
        formMain.append(plaintext);
        formMain.append(shiftKey);
        formMain.addCommand(enc);
        formMain.setCommandListener(this);
        display.setCurrent(formMain);        
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }
    
    public void showResult(){
        display = Display.getDisplay(this);
        String sPlainText = plaintext.getString().toUpperCase();
        int iShiftKey = Integer.parseInt(shiftKey.getString());
        
        iShiftKey = iShiftKey % 26;
        String cipherText = "";
        for(int i = 0;i < sPlainText.length();i++){
            int asciiValue = (int) sPlainText.charAt(i);
            if(asciiValue < 65 || asciiValue > 90){
                cipherText +=sPlainText.charAt(i);
                continue;
            }
            
            int basicValue = asciiValue - 65;
            int newAsciiValue = 65 + ((basicValue + iShiftKey) % 26);
            cipherText +=(char) newAsciiValue;
        }
        
        formResult = new Form("Result");
        formResult.append("Plain Text: " + sPlainText);
        formResult.append("chiper Text: " + cipherText);
        formResult.addCommand(new Command("Back",Command.BACK,1));
        formResult.setCommandListener(this);
        display.setCurrent(formResult);
        
        
    }
    
    public void commandAction(Command c,Displayable d){
        String label = c.getLabel();
        if(label.equals("ENC")){
            showResult();
        } else if(label.equals("Back")){
            display.setCurrent(formMain);
        }
        
    }
}
